package com.h117121.fashionshop.servletfilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.h117121.fashionshop.core.dom.Account;
import com.h117121.fashionshop.core.dom.Account.UserType;

@Component("roleCheckerInterceptor")
public class RoleChecker extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (request instanceof HttpServletRequest) {
			String servletPath = ((HttpServletRequest) request)
					.getServletPath();
			String contextPath = ((HttpServletRequest) request)
					.getContextPath();

			if (servletPath.startsWith("/admin")) {
				Account acc = (Account) request.getSession().getAttribute(
						"account");

				if (acc != null) {
					if (acc.getUserType() == UserType.ADMIN) {

					} else {
						response.sendRedirect(contextPath + "/home");
					}
				} else {
					response.sendRedirect(contextPath + "/login");
				}
			}
		}

		return true;
	}
}
